import streamlit as st
import threading as th
import draw.tables as tables
from st_bridge import bridge, html
import registry as reg
import time

st.set_page_config(
    page_title="Docker Registry",
    page_icon=":whale:",
    layout="wide",
    initial_sidebar_state="expanded",
)


def getV2(tableResult: dict):
    if "v2" not in tableResult:
        v2 = reg.getConfigV2()
        tableResult["v2"] = v2
    else:
        v2 = tableResult["v2"]
    v2 = reg.getConfigV2()
    return v2


def getData(tableResult: dict):
    v2 = getV2(tableResult)
    data = v2._catalog()
    result = []
    for one in data["repositories"]:
        tags = v2.tags(one)
        # times = []
        # for varsion in tags["tags"]:
        #     manifest = v2.manifest(tags["name"], varsion)
        #     NewTime = tables.getHistoryNewTime(manifest)
        #     times.append(NewTime)
        oneResult = {
            "name": tags["name"],
            "version": tags["tags"],
            "time": "none",
            "key": tags["name"] + ":" + tags["tags"][-1] + ":ALL",
        }
        result.append(oneResult)
    return result


def getVerstionData(tableResult: dict, name: str) -> dict:
    """
    拆分数据中的所有版本
    """
    v2 = getV2(tableResult)
    if "data" not in tableResult:
        return
    data = tableResult["data"]
    result = []
    for one in data:
        if one["name"] == name:
            for version in one["version"]:
                manifest = v2.manifest(name, version)
                NewTime = tables.getHistoryNewTime(manifest)
                oneResult = {
                    "name": name,
                    "version": [ version ],
                    "time": NewTime,
                    "key": name + ":" + version,
                }
                result.append(oneResult)
            break
    return result

def deleteData(tableResult: dict, name: str, version: str = None):
    """
    删除数据
    """
    v2 = getV2(tableResult)
    if "data" not in tableResult:
        return
    data: list = tableResult["data"]
    if version is None:
        for one in data:
            if one["name"] == name:
                versions = one["version"]
                for version in versions:
                    result = v2.delete(name, version)
                    if "errors" in result:
                        e = RuntimeError(result["errors"][0]["message"])
                        raise e
                data.remove(one)
    else:
        for one in data:
            if one["name"] == name:
                versions: list = one["version"]
                for oneVersion in versions:
                    if oneVersion == version:
                        result = v2.delete(name, version)
                        if "errors" in result:
                            e = RuntimeError(result["errors"][0]["message"])
                            raise e
                        versions.remove(oneVersion)
                        break
                break
    pass


def threadGetData(tableResult: dict):
    # if "forceUpdate" in tableResult and tableResult["forceUpdate"] == True:
    #     tableResult["forceUpdate"] = False
    # else:
    #     if "time" in tableResult and time.time() - tableResult["time"] < 60:
    #         return
    # # 解释代码: 如果没有time或者time距离上次更新超过60秒, 则更新
    # tableResult["time"] = time.time()
    result = getData(tableResult)
    if "data" not in tableResult:
        tableResult["data"] = result
    elif result != tableResult["data"]:
        tableResult["data"] = result
        tableResult["update"] = True
    # print(tableResult)
    # 打印时间格式 yyyy-dd-mm hh:mm:ss
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + " 同步")
    pass


if "tableResult" not in st.session_state:
    st.session_state["tableResult"] = {}
    pass

if "threads" not in st.session_state:
    st.session_state["threads"] = []
    threads = st.session_state["threads"]
else:
    threads = st.session_state["threads"]

threads: list[th.Thread]
if (
    "update" not in st.session_state["tableResult"]
    or st.session_state["tableResult"]["update"] is False
):
    if len(threads) == 0:
        threads.append(
            th.Thread(target=threadGetData, args=(st.session_state["tableResult"],))
        )
        threads[0].start()
        st.session_state["threads"] = threads
        pass
    elif not threads[0].is_alive():
        threads[0] = th.Thread(
            target=threadGetData, args=(st.session_state["tableResult"],)
        )
        threads[0].start()
        st.session_state["threads"] = threads
        pass
else:
    st.session_state["tableResult"]["update"] = False
    pass

if "data" not in st.session_state["tableResult"]:
    threads[0].join()

# if "clickData" not in st.session_state:
#     st.session_state["clickData"] = {}
#     clickData = st.session_state["clickData"]
# else:
#     clickData = st.session_state["clickData"]
#     pass

clickLine: str = bridge("Home", default=None)
# print(clickLine)
# if clickLine is not None and "old" in clickData and clickLine != clickData["old"]:
#     pass
# else:
#     tables.drawTables(st.session_state["tableResult"]["data"])

# clickData["old"] = clickLine
if clickLine is not None:
    tabs = ["Versions","Home"]
    Versions, Home = st.tabs(tabs)
    clickLineArr = clickLine.split(":")
    if len(clickLineArr) == 3:
        operation, name, version = clickLineArr
        Tfun = ""
    elif len(clickLineArr) == 4:
        operation, name, version, Tfun = clickLineArr
    print(operation, name, version, Tfun)
    if operation == "view":
        if "VersionsName" not in st.session_state or st.session_state["VersionsName"] != name:
            VersionsData = getVerstionData(st.session_state["tableResult"], name)
            st.session_state["VersionsData"] = VersionsData
            st.session_state["VersionsName"] = name
        else:
            VersionsData = st.session_state["VersionsData"]
        with Versions:
            st.title(f"{name} 版本管理")
            tables.drawTables(VersionsData,view=False)
    elif operation == "delete":
        if Tfun == "ALL":
            deleteData(st.session_state["tableResult"], name)
        else:
            deleteData(st.session_state["tableResult"], name, version)
else:
    tabs = ["Home"]
    Home = st.tabs(tabs)[0]

with Home:
    st.title("镜像管理")
    tables.drawTables(st.session_state["tableResult"]["data"])

st.markdown(
    """
    <style>
    div iframe[title="st_bridge.bridge.bridge"] {
        display: block; 
    }
    
    </style>
    """,
    unsafe_allow_html=True,
)

try:
    threads[0].join()
    if (
        "update" in st.session_state["tableResult"]
        and st.session_state["tableResult"]["update"]
    ):
        st.experimental_rerun()
        pass
except:
    pass
